import React, { useEffect, useState } from 'react';

const HOST = 'https://ai.gitee.com';

export default function ServerlessAPIServices() {
  const [loading, setLoading] = useState(true);
  const [services, setServices] = useState([]);
  const [showOperations, setShowOperations] = useState(false);
  const [error, setError] = useState(null);
  useEffect(() => {
    async function getOperations() {
      setLoading(true);
      const resp = await fetch(`${HOST}/api/pay/service/operations`);
      if (resp.status !== 200) {
        await getServices();
        return;
      }
      const items = await resp.json();
      setServices(
        items
          .map(({ operations, service }) => ({ ...service, operations }))
          .filter(({ tags }) => tags && tags.length > 0)
          .sort(({ created_at: c1 }, { created_at: c2 }) => (c1 < c2 ? 1 : -1)),
      );
      setShowOperations(true);
      setLoading(false);
    }
    async function getServices() {
      try {
        setLoading(true);
        const resp = await fetch(
          `${HOST}/api/pay/services?type=serverless&page=1&size=100`,
        );
        const { items } = await resp.json();
        setServices(
          items
            .filter(({ tags }) => tags && tags.length > 0)
            .sort(({ created_at: c1 }, { created_at: c2 }) =>
              c1 < c2 ? 1 : -1,
            ),
        );
      } catch (e) {
        console.error(e);
        setError(e.message);
        setServices([]);
      } finally {
        setLoading(false);
      }
    }
    getOperations();
  }, []);

  if (loading) {
    return (
      <p style={{ border: '1px solid #CCC', borderRadius: 4, padding: 10 }}>
        加载 Serverless API 服务列表...
      </p>
    );
  }

  if (services.length === 0) {
    return (
      <p
        style={{
          border: '1px solid #f44336',
          background: '#f44336',
          color: 'white',
          borderRadius: 4,
          padding: 10,
        }}
      >
        无法获取 Serverless API 服务列表，请向我们发送邮件反馈该问题：
        <a
          href="mailto:gitee-ai@oschina.cn"
          style={{ color: 'white', textDecoration: 'underline' }}
        >
          gitee-ai@oschina.cn
        </a>
        {error ? (
          <>
            <br />
            错误信息：{error}
          </>
        ) : (
          ''
        )}
      </p>
    );
  }

  return (
    <table>
      <thead>
        <tr>
          <th>模型名称</th>
          <th>分类</th>
          {showOperations && <th>接口</th>}
          <th>简介</th>
          <th style={{ textAlign: 'right' }}>上线时间</th>
        </tr>
      </thead>
      <tbody>
        {services.map(
          (
            { created_at, model_info, id, remark, tags, operations, ident },
            index,
          ) => (
            <tr key={index}>
              <td style={{ verticalAlign: 'middle' }}>
                <a
                  href={
                    ident
                      ? `${HOST}/serverless-api?model=${ident}`
                      : `${HOST}/serverless-api?service=${id}`
                  }
                  target="blank"
                >
                  {model_info.name}
                </a>
              </td>
              <td style={{ verticalAlign: 'middle' }} width={110}>
                {tags[0]?.name || '-'}
              </td>
              {showOperations && (
                <td width={200}>
                  {operations
                    ? operations.map((op, i) => (
                        <>
                          <a
                            key={i}
                            title={op.description}
                            href={`${HOST}/serverless-api?model=${ident}&operation=${op.id}`}
                            target="blank"
                          >
                            {op.name}
                          </a>
                          {i < operations.length - 1 ? '、' : ''}
                        </>
                      ))
                    : '-'}
                </td>
              )}
              <td style={{ verticalAlign: 'middle' }}>{remark}</td>
              <td style={{ verticalAlign: 'middle', textAlign: 'right' }}>
                {new Date(created_at).toLocaleDateString('zh-CN')}
              </td>
            </tr>
          ),
        )}
      </tbody>
    </table>
  );
}
